// index.js
// pages/home/home.js
import api from '../../utils/api.js';
import cache from '../../utils/cache.js';
import http from '../../utils/http.js';
import tools from '../../utils/tools.js';

const Http = new http;

Page({
  data: {
    userInfo: {
      headimgurl: "",
      nickName: "",
    },
    filePath: "",
  },
  onLoad() {
    this.getUserInfo();
  },
  getUserInfo() {
    Http.httpReq({
      url: api.getUserInfo,
    }).then(ret => {
      let data = ret.data.data;
      this.setData({
        "userInfo.nickName": data.nickname,
        "userInfo.headimgurl": data.headimgurl
      })
    })
  },
  onChooseAvatar(e) {
    const _this = this;
    const {
      avatarUrl
    } = e.detail
    _this.setData({
      "userInfo.avatarUrl": avatarUrl
    })

    // 上传头像
    wx.uploadFile({
      url: api.uploadFiles, //仅为示例，非真实的接口地址
      filePath: this.data.userInfo.avatarUrl,
      name: 'file',
      success(res) {
        const data = JSON.parse(res.data)
        if (data.code == 1) {
          _this.setData({
            "filePath": data.data[0],
            "userInfo.headimgurl": data.data[1]
          })
        }
      }
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    this.setData({
      "userInfo.nickName": nickName
    })
  },
  onFormSubmit() {
    if (this.data.userInfo.nickName == '') {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'error',
        duration: 2000
      });
      return;
    }

    if (this.data.userInfo.headimgurl == 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0' || this.data.userInfo.avatarUrl == '') {
      wx.showToast({
        title: '请选择头像',
        icon: 'error',
        duration: 2000
      });
      return;
    }

    var data = {
      nickname: this.data.userInfo.nickName,
    };
    if (this.data.filePath != '') {
      data.avatarUrl = this.data.filePath
    }

    Http.httpReq({
      url: api.setUserInfo,
      data: data,
      method: 'PUT'
    }).then(res => {
      if (res.data.code == 1) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          success: function () {
            // 跳转
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo
        })
      }
    })
  }
})